package com.nginx.web.config;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

@Component
public class ParamFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        try {
            if (servletRequest instanceof HttpServletRequest) {
                HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
                ModifyableHttpServletRequestWrapper requestWrapper =
                        new ModifyableHttpServletRequestWrapper(httpServletRequest);
                // 修改请求参数
                requestWrapper.putParameter("boolDel", null);
                requestWrapper.putParameter("createTime", null);
                requestWrapper.putParameter("updateTime", null);
                // 继续过滤链
                filterChain.doFilter(requestWrapper, servletResponse);
            }else{
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }

    }

    private static class ModifyableHttpServletRequestWrapper extends HttpServletRequestWrapper {
        private final Map<String, String[]> modifiableParameters;

        public ModifyableHttpServletRequestWrapper(HttpServletRequest request) {
            super(request);
            modifiableParameters = new HashMap<>();
            modifiableParameters.putAll(request.getParameterMap());
        }

        @Override
        public String getParameter(String name) {
            String[] values = modifiableParameters.get(name);
            if (values != null && values.length > 0) {
                return values[0];
            }
            return null;
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            return modifiableParameters;
        }

        @Override
        public Enumeration<String> getParameterNames() {
            return new Vector<>(modifiableParameters.keySet()).elements();
        }

        @Override
        public String[] getParameterValues(String name) {
            return modifiableParameters.get(name);
        }

        public void putParameter(String name, String value) {
            modifiableParameters.put(name, new String[]{value});
        }
    }

}
